import { BasicService } from '@/api/basic.api'
import { UserService } from '@/api/user.api'
import { BasicUtils } from '@/utils/basic.utils'
import { Avatar, Button } from '@nutui/nutui-react-taro'
import { View, Button as TButton, Input } from '@tarojs/components'
import React, { useState } from 'react'
import { useSelector } from 'react-redux'

const UserLoginChooseAvatar: React.FC = () => {
  const user = useSelector((state: any) => state.user.user)
  const [isChooseAvatar, setIsChooseAvatar] = useState<boolean>(false)
  const getWxAvatar = async (e: any) => {
    setAvatarUrl(e.detail.avatarUrl)
    setIsChooseAvatar(true)
  }
  const [avatarUrl, setAvatarUrl] = useState<string>(() => {
    return user?.avatar ?? `${process.env.TARO_APP_IMG_OSS_URL}mine/member-avatar.png`
  })
  const confirmBlur = (e: any) => {
    setNickname(e.detail.value)
  }
  const confirmSubmit = async () => {
    console.log(nickname)
    if (isChooseAvatar) {
      try {
        BasicUtils.startLoading()
        const { data, code, message } = await BasicService.fileUpload(avatarUrl, 'file')
        if (code === 200) {
          updateUserFunc(data[0])
        } else {
          BasicUtils.showToast(message)
        }
      } finally {
        BasicUtils.endLoading()
      }
    } else {
      updateUserFunc(user.avatar)
    }
  }
  const [sex] = useState<number>(() => {
    return user?.sex ?? 0
  })
  const updateUserFunc = async (avatar?: string) => {
    const obj = {
      avatar,
      nickname,
      sex: sex
    }
    const { data, code, message } = await UserService.updateUserInfo(obj)
    if (code === 200 && data) {
      BasicUtils.showToast(message)
    }
  }
  const [nickname, setNickname] = useState<string>(() => {
    return user?.nickname ?? '微信用户'
  })
  return (
    <>
      <View>
        <TButton openType="chooseAvatar" onChooseAvatar={(e) => getWxAvatar(e)}>
          <Avatar size={90} src={avatarUrl} />
        </TButton>
        <View>
          <Input type="nickname" value={nickname} onBlur={(e) => confirmBlur(e)} placeholder="请输入昵称" />
        </View>
        <View></View>
      </View>
      <View className="fixed bottom-10 w-[100%]">
        <Button block type="primary" onClick={confirmSubmit}>
          修改
        </Button>
      </View>
    </>
  )
}

export default UserLoginChooseAvatar
